package com.lxf.cn.service.ipml;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxf.cn.dao.UserMapper;
import com.lxf.cn.model.User;
import com.lxf.cn.model.UserExample;
import com.lxf.cn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by liaoxuefeng on 2018/11/8.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper ;


    @Override
    @Transactional
    public int save(JSONObject params) {

        String userName = params.getString("userName");
        String password = params.getString("password");
        String phone = params.getString("phone");

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setPhone(phone);

        int result = userMapper.insertSelective(user);

        if (result > 0) {
            //上面保存数据了

            return  user.getUserId();
        }


         return result ;
    }


    @Override
    public PageInfo findAllUser(int pageNum, int pageSize  , JSONObject params) {

        PageHelper.startPage(pageNum , pageSize);
        List<Map> pageList = userMapper.findAllUser(params);
        PageInfo pageInfo = new PageInfo(pageList);
        return pageInfo;
    }


    @Override
    public int updateUserByIds(JSONObject params) {
        List<Integer> userIds = null ;
        JSONArray userInfo = params.getJSONArray("userInfo");

        if(userInfo != null && userInfo.size() > 0){
            userIds = new ArrayList<>(userInfo.size()) ;
            for (int i = 0 ; i < userIds.size() ; i++){
                JSONObject obj =  userInfo.getJSONObject(i);
                userIds.add(obj.getInteger("userId"));
            }
        }

        UserExample userExample = new UserExample() ;
        userExample.createCriteria().andUserIdIn(userIds);


        User user = new User();
        user.setUserName("张三丰");

        //修改单个
        //userMapper.updateByPrimaryKeySelective(user);

        //修改多个
        return userMapper.updateByExampleSelective(user , userExample);

    }

    @Override
    public List<Map> getExcleDate() {
        System.out.printf("数据～～～～～～～～"+ userMapper.getExcleDate());
      return   userMapper.getExcleDate();

    }


    @Override
    public User findUser(JSONObject params) {
        return  userMapper.selectByUser(params);
    }
}
